package cn.yjr.config;

import com.alibaba.druid.pool.xa.DruidXADataSource;
import com.atomikos.jdbc.AtomikosDataSourceBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 多数据源配置 使用jta进行分布式事务控制
 */
@Configuration
public class DataSourceConfig {

    /**
     * 创建多个数据源 ds1xa 和 ds2xa
     * 此处的Primary，是设置一个Bean的优先级
     *
     * @return
     */
    @Primary
    @Bean(name = "ds1xa")
    @ConfigurationProperties(prefix = "spring.datasource.druid.ds1")
    public DruidXADataSource getXaDateSource1() {
        return new DruidXADataSource();
    }

    @Bean(name = "ds2xa")
    @ConfigurationProperties(prefix = "spring.datasource.druid.ds2")
    public DruidXADataSource getXaDateSource2() {
        return new DruidXADataSource();
    }

    @Bean(name = "ds1")
    public DataSource getDateSource1(@Qualifier("ds1xa") DruidXADataSource dataSource) {
        AtomikosDataSourceBean ds = new AtomikosDataSourceBean();
        ds.setXaDataSource(dataSource);
        ds.setUniqueResourceName("ds1");
        return ds;
    }

    @Bean(name = "ds2")
    public DataSource getDateSource2(@Qualifier("ds2xa") DruidXADataSource dataSource) {
        AtomikosDataSourceBean ds = new AtomikosDataSourceBean();
        ds.setXaDataSource(dataSource);
        ds.setUniqueResourceName("ds2");
        return ds;
    }


    /**
     * 将多个数据源注入到DynamicDataSource
     *
     * @param dataSource1
     * @param dataSource2
     * @return
     */
    @Bean(name = "dynamicDataSource")
    public DynamicDataSource getDynamicDataSource(@Qualifier("ds1") DataSource dataSource1,
                                                  @Qualifier("ds2") DataSource dataSource2) {
        Map<Object, Object> targetDataSource = new HashMap<>();
        targetDataSource.put(DataSourceType.DataBaseType.ds1, dataSource1);
        targetDataSource.put(DataSourceType.DataBaseType.ds2, dataSource2);
        DynamicDataSource dataSource = new DynamicDataSource();
        dataSource.setTargetDataSources(targetDataSource);
        dataSource.setDefaultTargetDataSource(dataSource1);
        return dataSource;
    }
}
